package com.monitor.spring.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

/**
 * 配置文件操作
 */
public class PropertiesUtil {

    public static Properties loadProperties(Class<?> clazz, String name) {
        Properties pro = new Properties();
        InputStream in = null;
        try {
            in = clazz.getResourceAsStream(name);
            pro.load(new BufferedReader(new InputStreamReader(in)));
        } catch (Exception e) {
            // throw new RuntimeException(e);
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (Exception e) {
            }
        }
        return pro;
    }

    public static Boolean getPropBool(Properties props, String key, Boolean def) {
        String s = props.getProperty(key, null);
        Boolean b = null;
        if (s != null) {
            if (s.equals("1") || s.equalsIgnoreCase("true")) {
                b = Boolean.TRUE;
            } else if (s.equals("0") || s.equalsIgnoreCase("false")) {
                b = Boolean.FALSE;
            }
        }
        if (b == null)
            b = def;
        return b;
    }


    /**
     * 加载带前缀的配置
     *
     * @param props  配置文件
     * @param prefix 前缀
     * @param out    输出
     * @param mode   key的类型 0为String 1为Integer
     * @param <T>    类型,可以为 String 或 Integer
     */
    public static <T> void loadSubConfig(Properties props, String prefix, Map<T, String> out, int mode) {
        for (Object k : props.keySet()) {
            if (k == null) continue;
            String key = k.toString();

            if (key.startsWith(prefix)) {
                final String pre = key.substring(prefix.length());
                if (mode == 0)
                    out.put((T) pre, props.getProperty(key));
                else if (mode == 1) {
                    final Integer i = Integer.parseInt(pre);
                    out.put((T) i, props.getProperty(key));
                }
                continue;
            }
        }
    }

}
